from PyQt5.QtWidgets import QMessageBox, QFileDialog
from PyQt5.QtCore import QObject, pyqtSignal
from qgis._core import QgsProject, QgsProviderRegistry, QgsVectorLayer
from qgis._gui import QgsLayerTreeMapCanvasBridge
from .layer_config import LAYER_PRIORITY, GROUP_MAPPING
from .utils import apply_fixed_style
from logger import logger

class Layer(QObject):
    # 定义加载完成信号
    map_loaded = pyqtSignal()

    def __init__(self,canvas):
        super(Layer, self).__init__()
        self.canvas = canvas
        # 图层桥梁
        self.bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(), self.canvas)
        self.sub_layers = None
        self.layers = []
        self.loaded_layers = {}

    def open_file(self):
        file_path, _ = QFileDialog.getOpenFileName(None, "打开海图", "", "S-57 文件 (*.000);;所有文件 (*)")
        if file_path:
            logger.info(f"打开文件: {file_path}")
            self.__load_map(file_path)

    def __load_map(self, path):
        self.__clear()
        self.__load_layer(path)
        self.__create_layer()
        self.__do_group()
        self.canvas.setLayers(self.layers)
        self.bridge.setCanvasLayers()
        self.__zoom_to_layers(self.layers)

    def __clear(self):
        logger.info("清除现有图层...")
        QgsProject.instance().removeAllMapLayers()

    def __load_layer(self,path):
        logger.info("查询子图层...")
        self.sub_layers = QgsProviderRegistry.instance().querySublayers(path)
        logger.info(f"找到 {len(self.sub_layers)} 个子图层")

        if not self.sub_layers:
            logger.info("未找到有效图层")
            QMessageBox.warning(None, "加载失败", "未找到有效图层")
            return

    def __create_layer(self):
        logger.info("\n加载图层顺序:")
        for i, layer_name in enumerate(LAYER_PRIORITY):
            logger.info(f"{i + 1}. {layer_name}")

            # 查找子图层
            sub = next((s for s in self.sub_layers if s.name() == layer_name), None)
            if not sub:
                logger.info(f"  --> 未找到 {layer_name}")
                continue

            # 创建图层
            logger.info(f"  --> 创建图层 {layer_name}")
            layer = QgsVectorLayer(sub.uri(), layer_name, sub.providerKey())
            if not layer.isValid():
                logger.info(f"  --> 无效图层: {layer_name}")
                continue

            self.layers.append(layer)
            self.loaded_layers[layer_name] = layer
            QgsProject.instance().addMapLayer(layer, False)

            try:
                # 应用样式
                apply_fixed_style(layer)

                # 强制更新范围
                if layer.extent().isNull():
                    layer.updateExtents()

            except Exception as e:
                logger.info(f"样式应用错误: {layer_name} - {str(e)}")

        if not self.layers:
            logger.info("没有可加载的图层")
            QMessageBox.critical(None, "加载失败", "没有找到可加载的有效图层")
            return
        logger.info("创建图层完成")

    def __do_group(self):
        root = QgsProject.instance().layerTreeRoot()
        for group_name, layer_names in GROUP_MAPPING.items():
            group = root.findGroup(group_name) or root.addGroup(group_name)
            for layer_name in layer_names:
                if layer_name in self.loaded_layers:
                    layer_node = group.addLayer(self.loaded_layers[layer_name])
                    if group_name == "基础要素":
                        if layer_name == "M_COVR":  # 仅M_COVR可见
                            layer_node.setItemVisibilityChecked(True)
                        else:  # 其他基础要素图层不可见
                            layer_node.setItemVisibilityChecked(False)
                    if group_name == "水深要素":
                        if layer_name == "SOUNDG":
                            layer_node.setItemVisibilityChecked(False)
                        else:
                            layer_node.setItemVisibilityChecked(True)
                        # 障碍物要素组设置为不可见
                    if group_name == "障碍物":
                        group.setItemVisibilityChecked(False)
                        layer_node.setItemVisibilityChecked(False)
                    if group_name == "区域":
                        if layer_name == "SBDARE":
                            layer_node.setItemVisibilityChecked(False)

    def __zoom_to_layers(self, layers):
        if not layers:
            return
        extent = layers[0].extent()
        for layer in layers[1:]:
            extent.combineExtentWith(layer.extent())
        extent.scale(0.8)
        self.canvas.setExtent(extent)
        self.canvas.refresh()

        # 触发地图加载完成信号
        self.map_loaded.emit()
        logger.info("地图加载完成信号已触发")
    